import json
import sys
import scrapy
from scrapy import Request, Selector

sys.path.append('../spiders')
from Taobao.items import TaobaoItem


class VIT(scrapy.Spider):
    name = 'vit'
    allowed_domains = ["victorioususa.com"]

    def start_requests(self):
        yield Request(url="https://www.victorioususa.com/")

    def parse(self, response, **kwargs):
        sels = Selector(response)
        sel_cates = sels.xpath('//div[@class="desktop-only"]/div/div/ul//li//div/div//ul//li')
        for i in sel_cates:
            url = "https://www.victorioususa.com" + i.xpath('./a/@href').extract_first() + "?page=1"
            yield Request(url=url, callback=self.parse_1)

    # 解析每个分类
    def parse_1(self, response, **kwargs):
        sels = Selector(response)
        sel_ceates = sels.xpath('//div[@class="innerer"]')
        for i in sel_ceates:
            item = TaobaoItem()  # 获取分类
            item["brand"] = sels.xpath("//h1[@class='pagetitle h3-style']/text()").extract_first()
            uri = i.xpath('./a/@href').extract_first().strip()
            urls = "https://www.victorioususa.com" + uri + ".js"
            item["PageUrl"] = "https://www.victorioususa.com" + uri
            yield Request(url=urls, callback=self.parse_json, cb_kwargs={'item': item})

        try:
            next_url = sels.xpath(
                "//a[@class='pagination__next inh-col underline underline--on-hover']/@href").extract_first()
            yield Request(url="https://www.victorioususa.com"+next_url, callback=self.parse_1)
        except:
            print("没有下一页了")

    def parse_json(self, response, **kwargs):
        jsonresp = json.loads(response.text)
        item = kwargs['item']
        if jsonresp.get("compare_at_price_max") == 0:
            item["price"] = str(jsonresp.get('price'))
            item['sprice'] = ""
            str2 = "." + item["price"][-2:]
            item["price"] = item["price"][0:len(item["price"]) - 2]
            item["price"] = item["price"] + str2
        else:
            item['sprice'] = str(jsonresp.get("price"))
            item["price"] = str(jsonresp.get('compare_at_price_max'))
            str3 = "." + item["sprice"][-2:]
            str4 = "." + item["price"][-2:]
            item["price"] = item["price"][0:len(item["price"]) - 2]
            item["sprice"] = item["sprice"][0:len(item["sprice"]) - 2]
            item["sprice"] = item["sprice"] + str3
            item["price"] = item["price"] + str4
        if item['sprice'] == item["price"]:
            item['sprice'] = ""
        item["title"] = jsonresp.get('title')
        item["image"] = "https" + jsonresp.get('featured_image')
        item["gallery"] = ""
        try:
            images = jsonresp.get('images')
            for img in images[1:]:
                item["gallery"] += str("https" + img)
                item["gallery"] += ";"
            item["gallery"] = item["gallery"][0:len(item["gallery"]) - 1]
        except:
            print("没有二级图片")
        item['sku'] = jsonresp.get('variants')[0]['sku']
        item["color"] = ""
        item['size'] = ""

        try:
            options = jsonresp.get('options')
            for option in options:
                if option['name'] == "Color" or "COLOR" or "color":
                    colors = option['values']
                    for col in colors:
                        item["color"] += col
                        item["color"] += ","
                    item["color"] = item["color"][0:len(item["color"]) - 1]
        except:
            print("没有颜色")

        try:
            options1 = jsonresp.get('options')
            for option1 in options1:
                if option1['name'] == "Size" or "Waist" or "size":
                    sizes = option1['values']
                    for size in sizes:
                        item["size"] += size
                        item["size"] += ","
                    item["size"] = item["size"][0:len(item["size"]) - 1]
        except:
            print("没有大小")
        item['description'] = jsonresp.get("description") or ""
        item['category'] = "Home||"+item["brand"]+"||"+item["title"]
        yield item
